9643. Catalan numbers
Catalan
numbers cn are
given by recurrence relation:
с0 = 1,
сn = , n > 0
Compute the n-th Catalan numbers modulo m.
Input. Two integers n (0 ≤ n ≤ 104) and m (0 < m ≤ 109).
Output. Print the value of cn mod m.
Sample
input |
Sample
output |
5
100 |
42 |
Catalan numbers
Rewrite the recurrence relation in the
form:
с0 = 1,
сn = c0cn-1
+ c1cn-2 + c2cn-3
+ ... + cn-1c0, if n > 0
For example,
·
с0 = 1
·
с1 = c0c0 = 1,
·
с2 = c0c1 + c1c0
= 1 + 1 = 2,
·
с3 = c0c2 + c1c1
+ c2c0 = 2 + 1 + 2 = 5,
·
с4 = c0c3 + c1c2
+ c2c1 + c3c0
= 5 + 2 + 2 + 5 = 14,
·
с5 = c0c4 + c1c3
+ c2c2 + c3c1
+ c4c0 = 14 + 5 + 4 + 5 + 14 = 42
Since the value
of сn is recalculated through all the previous values of c0, c1,
c2, ..., cn-1, then the values
of the Catalan numbers we shall store in linear array.
Algorithm realization
Declare an
array cat, where we'll store Catalan numbers: cat[i] = ci.
long long cat[10001];
Read the
input data.
scanf("%lld %lld",
&n, &m);
Compute the
Catalan numbers using the recurrent formula.
cat[0] = 1;
for (i = 1; i <= n; i++)
{
for (j = 0; j < i; j++)
cat[i] =
(cat[i] + cat[j] * cat[i - j - 1]) % m;
}
Print the n-th Catalan number.
printf("%lld\n", cat[n]);
Python realization
Read the input data.
n, m = map(int, input().split())
In the list
cat store Catalan numbers: cat[i]
= ci.
cat = [0] * (n + 1)
Compute the
Catalan numbers using the recurrent formula.
cat[0] = 1
for i in range(1, n + 1):
for j in range(i):
cat[i] = (cat[i] + cat[j] * cat[i - j - 1]) % m
Print the n-th Catalan number.
print(cat[n])